package testJDBC;

import com.mysql.cj.jdbc.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 刘远望
 * Date: 2025-05-15
 * Time: 20:20
 */
public class DButil {
    //数据源
    private static DataSource dataSource = null;
    //数据库连接
    private static final String URL = "jdbc:mysql://127.0.0.1:3306/java113?characterEncodng=utf8&alLowPublicKeyRetrieval=true&useSSL=false";
    //用户名
    private static final String USER = "root";
    //密码
    private static final String PASSWORD = "liuyvanwang";
    //静态代码块,当类加载到JVM时,执行数据的初始化
    static {
        MysqlDataSource mysqlDataSource = new MysqlDataSource();
        mysqlDataSource.setURL(URL);
        mysqlDataSource.setUser(USER);
        mysqlDataSource.setPassword(PASSWORD);

        dataSource = mysqlDataSource;
    }

    /**
     * 构造方法私有化, 方式new这个对象
     */
    private DButil () {

    }

    /**
     * 获取数据库连接
     * @return
     * @throws SQLException
     */
    public static Connection getConnection() throws SQLException {
        return dataSource.getConnection();
    }

    /**
     * 释放资源,关闭连接
     * @param resultSet
     * @param statement
     * @param connection
     */
    public static void close (ResultSet resultSet, Statement statement, Connection connection) {
        //从后往前依次释放资源
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
